package com.offcn.item.web.service.impl;

import com.alibaba.fastjson.JSON;
import com.offcn.entity.Result;
import com.offcn.item.web.service.PageService;
import com.offcn.sellergoods.entity.GoodsEntity;
import com.offcn.sellergoods.feign.GoodsFeign;
import com.offcn.sellergoods.feign.ItemCatFeign;
import com.offcn.sellergoods.pojo.Goods;
import com.offcn.sellergoods.pojo.GoodsDesc;
import com.offcn.sellergoods.pojo.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import springfox.documentation.spring.web.json.Json;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageServiceImpl implements PageService {


    @Autowired
    private GoodsFeign goodsFeign;

    @Autowired
    private ItemCatFeign itemCatFeign;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${pagepath}")
    private String pagePath;


    private Map<String ,Object> createHtmlData(Long spuId){
        Map<String ,Object> dataMap = new HashMap<>();
        // spu sku
        GoodsEntity goodsEntity = goodsFeign.findById(spuId).getData();
        Goods goods = goodsEntity.getGoods();
        GoodsDesc goodsDesc = goodsEntity.getGoodsDesc();
        List<Item> itemList = goodsEntity.getItemList();
        dataMap.put("goods",goods);
        dataMap.put("goodsDesc",goodsDesc);
        dataMap.put("itemList",itemList);
        dataMap.put("specificationList", JSON.parseArray(goodsDesc.getSpecificationItems(),Map.class));
        dataMap.put("imageList", JSON.parseArray(goodsDesc.getItemImages(),Map.class));
        dataMap.put("category1",itemCatFeign.findById(goods.getCategory1Id().intValue()).getData().getName());
        dataMap.put("category2",itemCatFeign.findById(goods.getCategory2Id().intValue()).getData().getName());
        dataMap.put("category3",itemCatFeign.findById(goods.getCategory3Id().intValue()).getData().getName());
        return dataMap;
    }

    @Override
    public void createHtml(Long spuId) {
        // 获取上下文对象
        Context context = new Context();
        Map<String ,Object> data = this.createHtmlData(spuId);
        context.setVariables(data);
        // 准备文件
        File dir = new File(pagePath);
        if (!dir.exists()){
            dir.mkdirs();
        }
        File file = new File(dir, spuId + ".html");
        // 填充页面
        try (PrintWriter writer = new PrintWriter(file,"UTF-8")){
            templateEngine.process("item",context,writer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
